<template>
  <div class="search-bar">
    <div
      class="search-bar-wrapper"
      @click="onSearchBarClick"
    >
      <van-icon
        name="search"
        size="15px"
        class="serch"
      />
      <input
        :focus="focus"
        :disabled="disabled"
        :maxlength="limit"
        :placeholder="hotSearch?hotSearch:'搜索'"
        placeholder-style="color:#ADB4BE"
        @input="onChange"
        @confirm="onConfirm"
        v-model="searchWord"
        confirm-type="search"
        type="text"
        class="search-bar-input"
      />
      <van-icon
        name="clear"
        size="14px"
        class="clear"
        @click="onClearClick"
        v-if="searchWord"
      />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    focus: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 50
    },
    hotSearch: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      searchWord: '',
      timeId: -1
    }
  },
  methods: {
    onSearchBarClick () {
      this.$emit('onClick')
    },
    onClearClick () {
      this.searchWord = ''
      this.$emit('onClearClick')
    },
    // 输入监听事件
    onChange (e) {
      const { value } = e.mp.detail
      clearTimeout(this.timeId)
      this.timeId = setTimeout(() => {
        this.$emit('onChange', value)
      }, 500)
    },
    // 键盘右下角确认键的单击事件
    onConfirm (e) {
      console.log('按下了键盘右下角的键')
      const { value } = e.mp.detail
      this.$emit('onConfirm', value)
    },
    setValue (res) {
      this.searchWord = res
    },
    getValue () {
      return this.searchWord
    }
  }
}
</script>

<style lang="scss" scoped>
.search-bar {
  padding: 30rpx 31rpx;
  .search-bar-wrapper {
    display: flex;
    align-items: center;
    background: #f5f7f9;
    border-radius: 80rpx;
    padding: 20rpx 34rpx;
    .search-bar-input {
      margin: 0 20rpx;
      flex: 1;
      font-size: 34rpx;
    }
    .search,
    .clear {
      display: flex;
      height: 100%;
      align-items: center;
    }
  }
}
</style>
